package com.chat.business.common.interceptor;

import com.chat.business.common.Context;
import com.chat.business.common.thread_local.UserIdThreadLocal;
import com.chat.common.common.constant.RedisKeyConstant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author wei kunJie
 * @date 2024/4/16 20:27:15
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    private RedisTemplate<String,Object> redisTemplate= Context.getBean("redisTemplate",RedisTemplate.class);;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取token
        String token = request.getHeader("token");
        log.info("chat-business-data-service TokenInterceptor拿到token:"+token);
        // 从redis中得到userId
        Long userId = (Long) redisTemplate.opsForValue().get(RedisKeyConstant.TOKEN_USER +token);
        log.info("chat-business-data-service TokenInterceptor拿到userId:"+userId);
        //保存userId,以便在controller或service中使用
        UserIdThreadLocal.set(userId);
        // 放行
        return true;
    }
}
